<template>
  <div class="container">
    <div class="app-container">
      <el-container>
        <!-- 布局头部 -->
        <el-header>
          <!-- 左边搜索框 -->
          <el-row type="flex" justify="space-between" style="margin-top: 25px">
            <el-col>
              <el-input
                v-model="queryParams.keyword"
                size="mini"
                style="width: 240px"
                prefix-icon="el-icon-search"
              />
            </el-col>
            <el-col>
              <div style="display: flex; justify-content: flex-end">
                <el-button
                  v-permission="'add-employee'"
                  size="mini"
                  type="primary"
                  @click="$router.push('/employee/detail')"
                >添加员工</el-button>
                <el-button
                  size="mini"
                  @click="showExcelDialog = true"
                >excel导入</el-button>
                <el-button size="mini" @click="exportAPI">excel导出</el-button>
              </div>
            </el-col>
          </el-row>
        </el-header>
        <el-container>
          <!-- 布局左边 -->
          <!-- 树形组件 -->
          <el-aside width="260px" height="100vh" style="margin-top: 10px">
            <el-tree
              ref="deptTree"
              node-key="id"
              :data="depts"
              :props="defaultProps"
              default-expand-all
              highlight-current
              @current-change="selectNode"
            />
          </el-aside>
          <!-- 布局右边 -->
          <el-main height="100%">
            <el-table :data="list">
              <el-table-column prop="staffPhoto" label="头像">
                <template v-slot="{ row }">
                  <el-avatar
                    v-if="row.staffPhoto"
                    :size="30"
                    :src="row.staffPhoto"
                  />
                  <span v-else class="username">{{
                    row.username?.charAt(0)
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="username" label="姓名" />
              <el-table-column prop="mobile" label="手机号" sortable />
              <el-table-column prop="workNumber" label="工号" sortable />
              <el-table-column prop="formOfEmployment" label="聘用形式">
                <template v-slot="{ row }">
                  <span>{{
                    row.formOfEmployment === 1 ? "正式" : "非正式"
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="departmentName" label="部门" />
              <el-table-column prop="timeOfEntry" label="入职时间" sortable />
              <el-table-column v-slot="{ row }" label="操作">
                <el-button type="text" @click="btnRole(row)">角色</el-button>
                <el-button
                  type="text"
                  @click="$router.push(`/employee/detail?id=${row.id}`)"
                >查看</el-button>
                <el-button type="text" @click="delRole(row)">删除</el-button>
              </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-row
              align="middle"
              style="height: 60px"
              type="flex"
              justify="end"
            >
              <el-pagination
                :total="total"
                layout="total,sizes, prev, pager, next"
                :page-sizes="[2, 5, 10, 20]"
                @current-change="currentChange"
                @size-change="sizeChange"
              />
            </el-row>
          </el-main>
        </el-container>
      </el-container>
    </div>
    <!-- 弹出框 -->
    <importExcel
      :show-excel-dialog="showExcelDialog"
      @update:showExcelDialog="updateShowExcelDialog"
      @uploadSuccess="getEmployeeListAPI"
    />
    <!-- 权限框 -->
    <el-dialog title="分配角色" :visible.sync="showRoleDialog">
      <el-form>
        <el-form-item>
          <el-checkbox-group v-model="roleIds">
            <el-checkbox
              v-for="item in roleList"
              :key="item.id"
              size="mini"
              :label="item.id"
            >{{ item.name }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item style="display: flex; justify-content: center">
          <el-button style="" @click="showRoleDialog = false">取 消</el-button>
          <el-button type="primary" @click="btnRoleOk">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import FileSaver from 'file-saver'
import { getDepartment } from '@/api/department'
import { transListToTreeData } from '@/utils/index'
import {
  getEmployeeList,
  exportAPI,
  delEmployee,
  getEnableRoleList,
  assignRole,
  getEmployeeDetail
} from '@/api/employee'
import importExcel from './components/import-excel.vue'
export default {
  name: 'Employee',
  components: { importExcel },
  data() {
    return {
      depts: [],
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      queryParams: {
        departmentId: null,
        page: 1,
        pagesize: 10,
        keyword: ''
      },
      list: [],
      total: 0,
      timer: null,
      showExcelDialog: false, // 下载excel文档
      showRoleDialog: false, // 控制角色弹窗
      roleIds: [], // 员工角色id数组
      roleList: [], // 角色数据
      currentUserId: null // 记录当前点击的用户id
    }
  },
  watch: {
    'queryParams.keyword'() {
      clearInterval(this.timer)
      this.timer = setTimeout(() => {
        this.queryParams.page = 1
        this.getEmployeeListAPI()
      }, 300)
    }
  },
  created() {
    this.getDepartmentAPI()
    this.getEnableRoleList()
  },
  methods: {
    async getDepartmentAPI() {
      // 获取树形数据
      this.depts = transListToTreeData(await getDepartment(), 0)
      this.queryParams.departmentId = this.depts[0].id // 拿到第一个id
      // 设置选中节点
      // 树组件渲染是异步的 等到更新完再设置
      this.$nextTick(async() => {
        this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId)
        this.getEmployeeListAPI()
      })
    },
    async getEmployeeListAPI() {
      const { total, rows } = await getEmployeeList(this.queryParams)
      this.list = rows
      this.total = total
    },
    selectNode(node) {
      // 设置树形节点id
      this.queryParams.departmentId = node.id
      this.queryParams.page = 1 // 设置第一页
      this.getEmployeeListAPI()
    },
    sizeChange(val) {
      // 每页数据改变触发
      this.queryParams.pagesize = val
      this.getEmployeeListAPI()
    },
    currentChange(val) {
      // 当前也改变触发
      this.queryParams.page = val
      this.getEmployeeListAPI()
    },
    async exportAPI() {
      // 导出export表格
      const res = await exportAPI()
      FileSaver.saveAs(res, '员工信息表.xlsx')
    },
    updateShowExcelDialog(flse) {
      // excel表格关闭
      this.showExcelDialog = flse
    },
    async delRole(row) {
      // 点击删除
      if (this.list.length === 1 && this.queryParams.page > 1) {
        this.queryParams.page--
      }
      this.getEmployeeListAPI()
      try {
        await delEmployee(row.id)
        this.$message.success('删除成功')
      } catch (error) {
        console.log(error)
      }
    },
    async getEnableRoleList() {
      // 获取角色
      const res = await getEnableRoleList()
      this.roleList = res
    },
    async btnRole(row) {
      // 点击角色
      const { roleIds } = await getEmployeeDetail(row.id)
      this.roleIds = roleIds
      this.currentUserId = row.id
      this.showRoleDialog = true
    },
    async btnRoleOk() {
      // 点击角色中确定
      await assignRole({
        id: this.currentUserId,
        roleIds: this.roleIds
      })
      this.$message.success('分配用户角色成功')
      this.showRoleDialog = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-main {
  padding-top: 0;
}
.username {
  height: 30px;
  width: 30px;
  line-height: 30px;
  text-align: center;
  border-radius: 50%;
  color: #fff;
  background: #04c9be;
  font-size: 12px;
  display: inline-block;
}
</style>
